package org.sklse.learningassistant.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author YuRun
 * @since 2017年12月9日
 * TODO tesseract version & thread safe
 */
public class TesseractUtils {

    public static String callTesseract(String imagePath) {
        System.out.println(imagePath);
        Process process = null;
        Runtime runtime = Runtime.getRuntime();
        try {

//            String[] cmd = {"D:\\ocr\\Tesseract-OCR\\tesseract", imagePath, "stdout","-l", "chi_sim"};
            String[] cmd = {"tesseract", imagePath, "stdout", "-l", "chi_sim"};
            process = runtime.exec(cmd);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        InputStream is = process.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String b;
        StringBuilder sb = new StringBuilder();
        try {
            while((b=br.readLine())!=null){
                sb.append(b);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
        return sb.toString();
    }
}
